<template>
    <view class="rx-date-range">
        <div v-if="readOnly" class="rx-disabled">{{ getCurrentValue(false) }}</div>
        <div v-else class="rx-date-center">
            <span  @click="showPlugin" :style="[value?'color: #555555':'color:#ccc']" class="rx-time-name">{{ getCurrentValue(true) }}</span>
            <my-icon class="rx-date-icon" @click="onAllowClear" :type="value?'icon-lineicon-test28':'icon-lineVue3_date'"></my-icon>
        </div>
        <lingfeng-timepicker ref="dateRange" :type="dateMode" :defaultData="defaultData" :maxDate="maxDate"
                             :minDate="minDate" @change="confirm"></lingfeng-timepicker>
    </view>
</template>

<script>
/**
 * 日期范围控件
 */
import MForm from '../js/MForm';
import dayjs from "dayjs";
import weekOfYear from 'dayjs/plugin/weekOfYear';

export default {
    name: "MDateRange",
    mixins: [MForm],
    data() {
        return {
            dateMode: "date-range",
            params: {},
            defaultData: {
                startTime: "2025 第1周",
                endTime: "2026 第1周"
            },
        }
    },
    computed: {
        maxDate() {
            let conf = this.metadata.options;
            let maxDate = {};
            if (conf.relate && conf.relate != 'none') {
                if (['today', 'field'].includes(conf.relate)) {
                    let dateObj;
                    if (conf.relate == 'field') {
                        let compareDate = this.data[conf.relateField];
                        if (!compareDate) {
                            maxDate.year = dayjs().year() + 10;
                            return maxDate;
                        }
                        dateObj = dayjs(compareDate);
                    } else {
                        dateObj = dayjs();
                    }
                    let year = dateObj.year();
                    let month = dateObj.month() + 1;
                    let date = dateObj.date()
                    let hour = dateObj.hour()
                    let minute = dateObj.minute()
                    let second = dateObj.second()
                    if (conf.compare == 'gt') {
                        //大于
                        maxDate = {
                            year: year,
                            month: month,
                            date: date,
                            hour: hour,
                            minute: minute,
                            second: second,
                        }
                    } else if (conf.compare == 'ge') {
                        //大于等于
                        maxDate = {
                            year: year,
                            month: month,
                            date: Object.keys(this.params).length == 0 ? date - 1 : date,
                            hour: hour,
                            minute: this.params.second ? minute : minute - 1,
                            second: this.params.second ? second - 1 : second,
                        }
                    }
                } else {
                    maxDate.year = dayjs().year() + 10;
                }
            } else {
                maxDate.year = dayjs().year() + 10;
            }
            return maxDate;
        },
        minDate() {
            let conf = this.metadata.options;
            let minDate = {};
            if (conf.relate && conf.relate != 'none') {
                if (['today', 'field'].includes(conf.relate)) {
                    let dateObj;
                    if (conf.relate == 'field') {
                        let compareDate = this.data[conf.relateField];
                        if (!compareDate) {
                            return minDate;
                        }
                        dateObj = dayjs(compareDate);
                    } else {
                        dateObj = dayjs();
                    }
                    let year = dateObj.year();
                    let month = dateObj.month() + 1;
                    let date = dateObj.date()
                    let hour = dateObj.hour()
                    let minute = dateObj.minute()
                    let second = dateObj.second()
                    if (conf.compare == 'lt') {
                        //小于
                        minDate = {
                            year: year,
                            month: month,
                            date: date,
                            hour: hour,
                            minute: minute,
                            second: second,
                        }
                    } else if (conf.compare == 'le') {
                        //小于等于
                        minDate = {
                            year: year,
                            month: month,
                            date: Object.keys(this.params).length == 0 ? date + 1 : date,
                            hour: hour,
                            minute: this.params.second ? minute : minute + 1,
                            second: this.params.second ? second + 1 : second,
                        }
                    }
                }
            }
            return minDate;
        }
    },
    created() {
        dayjs.extend(weekOfYear);
        this.init();
    },
    methods: {
        i18n(name,text,key){
            return this.$ti18(name,text,"componentsLang",key);
        },
        getCurrentValue(val) {
            let value = val?this.$ti18('rxDecorator.select', "请选择"):'';
            if (this.defaultData.startTime  && this.defaultData.endTime) {
                value =this.defaultData.startTime + " - " + this.defaultData.endTime;
            }
            return value;
        },
        showPlugin() {
            this.$refs.dateRange.show();
        },
        isNumber(val) {
            return typeof val === 'number';
        },
        confirm(value) {
            if (value instanceof Object && value.hasOwnProperty("show")) {
                return;
            }
            value =  value.map(res=>{
                return this.isNumber(res)?JSON.stringify(res):res
            })
            let conf = this.metadata.options;
            if (['week'].includes(conf.ctlType)) {
                let startTime = value[0].replace(" ", "-").replace(this.i18n('de','第'), "").replace(this.i18n('circumference','周'), "");
                let endTime = value[1].replace(" ", "-").replace(this.i18n('de','第'), "").replace(this.i18n('circumference','周'), "");
                let curValue = startTime + "," + endTime;
                this.setData(curValue);
                return;
            }
            let startDate = dayjs(value[0]).toDate();
            let endDate = dayjs(value[1]).toDate();
            let startTime = this.getDateTime(startDate);
            let endTime = this.getDateTime(endDate);
            let curValue = startTime + "," + endTime;
            this.setData(curValue);
        },
        getDateTime(value) {
            let conf = this.metadata.options;
            let date = dayjs(value).toDate();
            var Y = date.getFullYear() + "";
            var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
            var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
            let v = Y;
            if (conf.format.includes('/')) {
                if (['date', 'month'].includes(conf.ctlType)) {
                    v += "/" + M;
                }
                if (['date'].includes(conf.ctlType)) {
                    v += "/" + D;
                }
            } else {
                if (['date', 'month'].includes(conf.ctlType)) {
                    v += "-" + M;
                }
                if (['date'].includes(conf.ctlType)) {
                    v += "-" + D;
                }
            }
            if (this.params.hour) {
                var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours());
                v += " " + h;
            }
            if (this.params.minute) {
                var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
                v += ":" + m;
            }
            if (this.params.second) {
                var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
                v += ":" + s;
            }
            return v;
        },
        initDate(format, conf) {
            // 判断格式日期
            if (format == 'YYYY-MM-DD HH:mm:ss') {
                this.dateMode = "datetime-all-range";
                this.params.hour = true;
                this.params.minute = true;
                this.params.second = true;
            }
            if (format == 'YYYY-MM-DD HH:mm:00') {
                this.dateMode = "datetime-all-range";
                this.params.hour = true;
                this.params.minute = true;
                this.params.second = true;
            } else if (format == 'YYYY-MM-DD HH:mm') {
                this.dateMode = "datetime-range";
                this.params.hour = true;
                this.params.minute = true;
            }
            return true;
        },
        init() {
            let conf = this.metadata.options;
            var format = conf.format;
            let curValue = this.value;
            if (conf.ctlType == 'date') {
                this.initDate(format, conf);
            } else if (conf.ctlType == 'month' ) {
                this.dateMode = 'year-month-range';
            } else if (conf.ctlType == 'year' ) {
                this.dateMode = 'year-range';
            } else if (conf.ctlType == 'week') {
                this.dateMode = "week-range";
                // 默认选中当前时间
                if (this.value == "" && conf.defaultValue) {
                    let curDate = dayjs();
                    let startTime = curDate.year() + "-" + curDate.week();
                    let endTime = curDate.year() + "-" + curDate.week();
                    curValue = startTime + "," + endTime;
                }
            }
            this.setCurValue(curValue);
        },
        setCurValue(val){
            if (val) {
                let ary = val.split(",");
                if (["week-range"].includes(this.dateMode)) {
                    let startAry = ary[0].split("-");
                    let endAry = ary[1].split("-");
                    this.defaultData.startTime = startAry[0] +' '+ this.i18n('de','第') + startAry[1] + this.i18n('circumference','周');
                    this.defaultData.endTime = endAry[0]+' ' +this.i18n('de','第') + endAry[1] + this.i18n('circumference','周');
                } else {
                    this.defaultData.startTime = ary[0];
                    this.defaultData.endTime = ary[1];
                }
            } else {
                this.defaultData.startTime = "";
                this.defaultData.endTime = "";
                if (["week-range"].includes(this.dateMode)) {
                   let year =  dayjs().year();
                    this.defaultData.startTime = year +' '+ this.i18n('de','第') + 1 + this.i18n('circumference','周');
                    this.defaultData.endTime = year +' ' +this.i18n('de','第') + 2 + this.i18n('circumference','周');
                }
            }
        },
        onAllowClear(){
            this.setData('');
        },
    },
    watch: {
        value: function (val, oldVal) {
            this.setCurValue(val);
        },
    },
}
</script>
<style scoped>
.rx-date-center{
    border-radius: 5px;
    border: 0.03rem solid rgba(232, 232, 232, 1);
    display: flex;
    justify-content: flex-start;
    align-items: center;
    padding: 0.5rem 0.5rem;
}
.rx-time-name{
    flex: 1;
    color: #555555;
    margin-right: 0.5rem;
}
.rx-disabled{
    background: rgba(245, 246, 249, 1);
    display: flex;
    align-items: center;
    padding: 0.5rem;
    border-radius: 4px;
    border: none;
    min-height: 1rem;
}
.rx-date-icon{
    font-size: 0.9rem;
    color: rgba(0, 0, 0, 0.2);
}
</style>
